<?php
/**
 * author:式神(289650682@qq.com)
 * time:2017-03-08
 */
namespace App\Http\Controllers\Admin;

use App\Http\Models\AdminUser;
use App\Http\Models\Permission;
use App\Http\Models\Role;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;

class UserController extends CommonController
{
	//用户列表
    public function userList(Request $request){
        if($request->isMethod('post')){
            $pagenum=config('system.page_num');
            $p=Input::get('p')?Input::get('p'):1;
            $json=[];
            $model=new AdminUser();
            $count=$model->count();
            $list=$model->skip(($p-1)*$pagenum)->take($pagenum)->orderBy('id','asc')->get()->toArray();

            $data['list']=$list;
            $data['title']=trans('config.usertitle');
            $json['status']=200;
            $json['pages']=ceil($count/$pagenum);
            $json['data']=$data;
            return $json;
        }
    	return view('admin.user.list');
    }
    /**
     * 添加管理员
     * @param Request $request
     * @return post
     */
    public function userAdd(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token','id');
            DB::beginTransaction();
            $data=[];
            try{
                AdminUser::create($input);
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                $data['url']='reload';
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }
    //编辑
    public function userEdit(Request $request){
        if($request->isMethod('post')){
            if(Input::get('password')!=""){
                $input=Input::except('_token','id');
                $input['password']=bcrypt($input['password']);
            }else{
                $input=Input::except('_token','id','password');
            }
            DB::beginTransaction();
            $model=new AdminUser();
            try{
                $model->where('id',Input::get('id'))->update($input);
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                if(!isset($input['status'])){
                    $data['url']='reload';
                }
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }
    public function userEditRole(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token','id');

            $admin = AdminUser::where('id',Input::get('id'))->first();
            DB::beginTransaction();
            try{
                DB::table('role_user')->where('user_id',Input::get('id'))->delete();
                if(isset($input['role']) && count($input['role'])>0){
                    foreach($input['role'] as $v){
                        $admin->attachRole($v);
                    }
                }
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
        $id=Input::get('id');
        $data=AdminUser::find($id);
        $roleuser=$data->RoleUser;
        $role = Role::all();
        $child=[];
        foreach($roleuser as $v){
            $child[]=$v['role_id'];
        }
        return view('admin.user.editrole',compact('data','child','role'));
    }

    public function userDel(Request $request){
        if($request->isMethod('post')){
            $id=Input::get('id');
            $id=explode(",", $id);
            $m=new AdminUser();
            try{
                $m->whereIn('id',$id)->delete();
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                $data['url']='reload';
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }


    /**
     * 角色列表
     * @param Request $request
     * @return get返回view  post返回json
     */
    public function roleList(Request $request){
        if($request->isMethod('post')){
            $pagenum=config('system.page_num');
            $p=Input::get('p')?Input::get('p'):1;
            $json=[];
            $roles=new Role();
            $count=$roles->count();
            $role=$roles->skip(($p-1)*$pagenum)->take($pagenum)->orderBy('id','asc')->get()->toArray();
            $data['list']=$role;
            $data['title']=trans('config.roletitle');
            $json['status']=200;
            $json['pages']=ceil($count/$pagenum);
            $json['data']=$data;
            return $json;
        }
        return view('admin.role.list');
    }

    /**
     * 添加角色
     * @param Request $request
     * @return post
     */
    public function roleAdd(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token');
            DB::beginTransaction();
            $data=[];
            try{
                $role=new Role();
                foreach ($input as $k=>$v){
                    $role->$k=$v;
                }
                $role->save();
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                $data['url']='reload';
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }
    //编辑
    public function roleEdit(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token','id');
            $role=new Role();
            try{
                foreach ($input as $k=>$v){
                    $role->$k=$v;
                }
                $role->where('id',Input::get('id'))->update($input);
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                if(!isset($input['status'])){
                    $data['url']='reload';
                }
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }else{
            $id=Input::get('id')?Input::get('id'):0;
            if($id==0){
                return trans('config.return_error');
            }
            $data=Role::where('id',$id)->first();
            return view('admin.role.edit',compact('data'));
        }
    }

    //设置角色权限
    public function roleSet(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token');
            $m=new Role();
            $role = $m->where('id',$input['id'])->first();
            DB::beginTransaction();
            try{
                DB::table('permission_role')->where('role_id',$input['id'])->delete();
                if(isset($input['per_id']) && count($input['per_id'])>0){
                    foreach($input['per_id'] as $v){
                        $role->attachPermission($v);
                    }
                }
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }else{
            $id=$request->input('id');
            $role=Role::find($id);
            $permission=$role->PermissionRole;
            $child=[];
            foreach($permission as $v){
                $child[]=$v['permission_id'];
            }
            $model=new Permission();
            $list=$model->orderBy('listsort','asc')->get();
            $data=cattree($list);
            return view('admin.role.set',compact('data','role','child'));
        }
    }

    //删除角色
    public function roleDel(Request $request){
        if($request->isMethod('post')){
            $id=Input::get('id');
            $id=explode(",", $id);
            $role=new Role();
            try{
                $role->whereIn('id',$id)->delete();
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                $data['url']='reload';
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }


    /**
     * 权限列表
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function permissionList(Request $request){
        if($request->isMethod('post')){
            $json=[];
            $model=new Permission();
            $list=$model->orderBy('listsort','asc')->get();
            $list=pertree($list);
            $data['list']=$list;
            $data['title']=trans('config.usertitle');
            $json['status']=200;
            $json['data']=$data;
            return $json;
        }
        return view('admin.permission.list');
    }

    //权限添加
    public function permissionAdd(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token');
            DB::beginTransaction();
            $data=[];
            try{
                Permission::create($input);
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                $data['url']='reload';
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }

    //许可修改
    public function permissionEdit(Request $request){
        if($request->isMethod('post')){
            $input=Input::except('_token','id');
            $model=new Permission();
            DB::beginTransaction();
            try{
                $model->where('id',Input::get('id'))->update($input);
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                if(!isset($input['status']) && !isset($input['showed'])){
                    $data['url']='reload';
                }
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }else{
            $id=Input::get('id')?Input::get('id'):0;
            if($id==0){
                return trans('config.return_error');
            }
            $model=new Permission();
            $data=$model->where('id',$id)->first();
            $list=$model->orderBy('listsort','asc')->where('showed',1)->get();
            $ids=getChildsId($list,$id);
            array_push($ids,$id);
            $permission=catlist($list);
            return view('admin.permission.edit',compact('data','permission','ids'));
        }
    }
    //删除许可
    public function permissionDel(Request $request){
        if($request->isMethod('post')){
            $id=Input::get('id');
            $id=explode(",", $id);
            $m=new Permission();
            DB::beginTransaction();
            try{
                $m->whereIn('id',$id)->delete();
                DB::commit();
                $data['status']=200;
                $data['msg']=trans('config.submit_success');
                $data['url']='reload';
            }catch (\Exception $e) {
                DB::rollBack();
                $data['status']=300;
                $data['msg']=trans('config.submit_error');
            }
            return $data;
        }
    }
}
